﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace WebApiTest
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void ClientShouldBeRunning()
        {
            Assert.IsNotNull(GetClient());
        }

        [TestMethod]
        public void T1()
        {
            var client = GetClient();

            var response = client.GetAsync("api/values").Result;  // Blocking call!
            var items = response.Content.ReadAsAsync<IEnumerable<string>>().Result;

            Assert.IsTrue(response.IsSuccessStatusCode);
            Assert.AreEqual(2, items.Count());

            response = client.GetAsync("api/values/1").Result;  // Blocking call!
            var item = response.Content.ReadAsAsync<string>().Result;

            Assert.AreEqual("1", item);
        }

        [TestMethod]
        public void T2()
        {
            var client = GetClient();

            var response = client.PostAsJsonAsync("api/values", new { id = 3, value = "3" }).Result;  // Blocking call!
            Assert.IsTrue(response.IsSuccessStatusCode);

            response = client.PutAsJsonAsync("api/values", new { id = 3, value = "3_" }).Result;  // Blocking call!
            Assert.IsTrue(response.IsSuccessStatusCode);

            var item = client.GetAsync("api/values/3").Result.Content.ReadAsAsync<string>().Result;
            Assert.AreEqual("3_", item);

            response = client.DeleteAsync("api/values/3").Result;
            Assert.IsTrue(response.IsSuccessStatusCode);

            item = client.GetAsync("api/values/3").Result.Content.ReadAsAsync<string>().Result;
            Assert.IsNull(item);
        }



        private static HttpClient GetClient()
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:28845/");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            return client;
        }
    }
}
